package com.zwb.boot.controller;

import com.zwb.boot.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author 头发又黑又长
 * @Date 2022/7/22 18:05
 * @email zwb15083976291@163.com
 */
@Api("通用管理")
@Slf4j
@Controller
@RequestMapping("/common")
public class CommonController {

    private String filePath;


    public CommonController(@Value("${reggie.path}") String filePath) {
        this.filePath = filePath;
        File file = new File(this.filePath);
        // 判断文件夹是否存在，不存在创建
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "文件上传接口")
    @ResponseBody
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = null;
        try {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        } catch (Exception e) {
            log.info(e.getMessage());
            return R.error("请上传合法的图片文件");
        }
        String filename = UUID.randomUUID().toString() + suffix;
        try {
            file.transferTo(new File(this.filePath + File.separator + filename));
        } catch (IOException ioException) {
            log.error(ioException.getMessage());
            return R.success("文件上传失败！");
        }
        return R.success(filename);
    }


    /**
     * 文件下载
     *
     * @param name
     * @return
     */
    @ApiOperation(value = "文件下载接口")
    @GetMapping("/download")
    public void download(@RequestParam("name") String name, HttpServletResponse response) throws IOException {

        // 获取文件
        File file = new File(this.filePath + File.separator + name);
        if (!file.exists()) {
            response.setStatus(HttpStatus.NOT_FOUND.value());
            response.setContentType("text/html;charset=utf8");
            response.getWriter().write("文件不存在.....");
            return;
        }
        response.setContentType("image/jpeg");
        try {
            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
